import type { HeadConfig } from 'vitepress'

export interface CdnLibrary {
  name: string
  version: string
  css?: string[]
  js: string[]
  globalName: string
  testGlobal: string
}

const CDN_LIBRARIES: CdnLibrary[] = [
  {
    name: 'swiper',
    version: '11.2.10',
    css: ['swiper-bundle.min.css'],
    js: ['swiper-bundle.min.js'],
    globalName: 'Swiper',
    testGlobal: 'window.Swiper'
  },
  {
    name: 'vue3-toastify',
    version: '0.2.8',
    css: ['dist/index.css'],
    js: ['dist/index.js'],
    globalName: 'Vue3Toastify',
    testGlobal: 'window.Vue3Toastify'
  },
  {
    name: 'dayjs',
    version: '1.11.13',
    js: ['dayjs.min.js'],
    globalName: 'dayjs',
    testGlobal: 'window.dayjs'
  },
  {
    name: 'floating-vue',
    version: '5.2.2',
    css: ['dist/style.css'],
    js: ['dist/floating-vue.umd.js'],
    globalName: 'FloatingVue',
    testGlobal: 'window.FloatingVue'
  }
]

const CDN_PROVIDERS = [
  'https://cdn.jsdelivr.net/npm',
  'https://unpkg.com',
  'https://cdnjs.cloudflare.com/ajax/libs'
]

function generateLibraryUrl(provider: string, lib: CdnLibrary, file: string): string {
  if (provider.includes('cdnjs')) {
    // cdnjs 使用不同的路径结构
    const cdnJsMap: Record<string, string> = {
      'swiper': 'Swiper',
      'dayjs': 'dayjs',
      'vue3-toastify': 'vue3-toastify',
      'floating-vue': 'floating-vue'
    }
    const cdnJsName = cdnJsMap[lib.name] || lib.name
    return `${provider}/${cdnJsName}/${lib.version}/${file}`
  }
  return `${provider}/${lib.name}@${lib.version}/${file}`
}

function generateFallbackScript(lib: CdnLibrary): string {
  const fallbackProviders = CDN_PROVIDERS.slice(1) // 排除主源

  let script = `
  (function() {
    let retryCount = 0;
    const maxRetries = ${fallbackProviders.length};

    function checkAndLoad() {
      if (${lib.testGlobal} !== undefined) return;

      if (retryCount >= maxRetries) {
        console.warn('Failed to load ${lib.name} from all CDN sources');
        return;
      }

      const provider = ${JSON.stringify(fallbackProviders)}[retryCount];
      retryCount++;

      console.log('Loading ${lib.name} from fallback CDN:', provider);

      // 加载 CSS
      ${lib.css ? lib.css.map(cssFile => `
      const css${cssFile.replace(/[^a-zA-Z0-9]/g, '')} = document.createElement('link');
      css${cssFile.replace(/[^a-zA-Z0-9]/g, '')}.rel = 'stylesheet';
      css${cssFile.replace(/[^a-zA-Z0-9]/g, '')}.href = provider + '/${lib.name}@${lib.version}/${cssFile}';
      document.head.appendChild(css${cssFile.replace(/[^a-zA-Z0-9]/g, '')});
      `).join('') : ''}

      // 加载 JS
      ${lib.js.map(jsFile => `
      const script${jsFile.replace(/[^a-zA-Z0-9]/g, '')} = document.createElement('script');
      script${jsFile.replace(/[^a-zA-Z0-9]/g, '')}.src = provider + '/${lib.name}@${lib.version}/${jsFile}';
      script${jsFile.replace(/[^a-zA-Z0-9]/g, '')}.onload = function() {
        console.log('Successfully loaded ${lib.name} from:', provider);
      };
      script${jsFile.replace(/[^a-zA-Z0-9]/g, '')}.onerror = function() {
        console.warn('Failed to load ${lib.name} from:', provider);
        setTimeout(checkAndLoad, 100);
      };
      document.head.appendChild(script${jsFile.replace(/[^a-zA-Z0-9]/g, '')});
      `).join('')}
    }

    // 延迟检查，确保主源有机会加载
    setTimeout(checkAndLoad, 1000);
  })();
  `

  return script.trim()
}

export function generateCdnScripts(): HeadConfig[] {
  const head: HeadConfig[] = []
  const primaryProvider = CDN_PROVIDERS[0] // jsdelivr

  CDN_LIBRARIES.forEach(lib => {
    // 加载主源 CSS
    if (lib.css) {
      lib.css.forEach(cssFile => {
        head.push([
          'link',
          {
            rel: 'stylesheet',
            href: generateLibraryUrl(primaryProvider, lib, cssFile),
            crossorigin: 'anonymous'
          }
        ])
      })
    }

    // 加载主源 JS
    lib.js.forEach(jsFile => {
      head.push([
        'script',
        {
          defer: '',
          src: generateLibraryUrl(primaryProvider, lib, jsFile),
          crossorigin: 'anonymous'
        }
      ])
    })

    // 添加 fallback 脚本
    head.push([
      'script',
      {},
      generateFallbackScript(lib)
    ])
  })

  return head
}

// 生成 Vite externals 配置
export function generateExternals() {
  const external: string[] = []
  const globals: Record<string, string> = {}

  CDN_LIBRARIES.forEach(lib => {
    external.push(lib.name)
    globals[lib.name] = lib.globalName
  })

  return { external, globals }
}
